package com.ny.zmb.openapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ny.zmb.openapi.entity.PmSms;
import com.ny.zmb.openapi.mapper.PmSmsMapper;
import com.ny.zmb.openapi.service.IPmSmsService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PmSmsServiceImp extends ServiceImpl<PmSmsMapper, PmSms> implements IPmSmsService {
    @Override
    public void saveSendPhone(String mobile, String random,String ip) {
        Long timeMillis = System.currentTimeMillis();
        Long time = timeMillis / 1000;
        PmSms sms = PmSms.builder()
                .code(random)
                .mobile(mobile)
                .event("shop_register")
                .createtime(time.intValue())
                .times(0)
                .ip(ip)
                .build();
        this.baseMapper.insertOrUpdate(sms);
    }

    @Override
    public Boolean verifyMobile(String mobile, String code) {
        LambdaQueryWrapper<PmSms> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PmSms::getMobile,mobile);
        wrapper.eq(PmSms::getEvent,"shop_register");
        wrapper.eq(PmSms::getTimes,"0");
        wrapper.orderByDesc(PmSms::getCreatetime);
        List<PmSms> pmSms = this.baseMapper.selectList(wrapper);
        if (null == pmSms || pmSms.size() == 0){
            return false;
        }
        PmSms sms = pmSms.get(0);
        sms.setTimes(sms.getTimes() + 1);
        this.baseMapper.updateById(sms);
        if (!sms.getCode().equals(code)){
            throw new RuntimeException("验证码不正确!");
        }
        if (sms.getTimes() <= 3){
            sms.setTimes(4);
            this.baseMapper.updateById(sms);
            return true;
        }
        return false;
    }
}
